package ini

import (
	"bufio"
	"errors"
	"io"
	"os"
	"runtime"
	"strings"
)

var CommentSymbol byte

func Init() { //判断os类型并处理不同的注释类型
	sysType := runtime.GOOS
	if sysType == "linux" {
		CommentSymbol = '#'
	}
	if sysType == "windows" {
		CommentSymbol = ';'
	}
}

type node map[string]string
type conf map[string][]node
type Listener interface {
	Listen(inifile string)
}

func Watch(filename string, listener Listener) (conf, error) {
	listener.Listen(filename)
	c := make(conf)
	var e error = nil
	f, err := os.Open(filename)
	if err != nil {
		e = errors.New("打开错误") //自定义错误
		return c, e
	}
	defer f.Close()
	r := bufio.NewReader(f)
	section := ""
	for {
		line, err := r.ReadString('\n')
		if err == io.EOF {
			break
		}
		if err != nil {
			e = errors.New("读取错误") //自定义错误
			break
		}
		line = strings.TrimSpace(line)

		if line == "" {
			continue
		}
		if line[0] == CommentSymbol {
			continue
		}
		length := len(line)
		if line[0] == '[' && line[length-1] == ']' {
			section = line[1 : length-1]
			if _, ok := c[section]; !ok {
				c[section] = []node{}
			}
		} else {
			s := strings.Split(line, "=")
			if len(s) < 2 {
				e = errors.New("输入错误") //自定义错误
				break
			}
			key := strings.TrimSpace(s[0])
			value := strings.TrimSpace(s[1])
			element := make(node)
			element[key] = value
			if section == "" {
				c[section] = []node{}
			}
			if _, ok := c[section]; ok {
				c[section] = append(c[section], element)
			}
		}
	}
	return c, e
}
